/**
 * 
 */
package com.ws.framework.remoteservice.core.protocal;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.logging.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * @author WSH
 *
 */
public class TransportIn extends LengthFieldBasedFrameDecoder {

	private Logger log = Logger.getLogger(this.getClass().getName());
	
	public TransportIn() {
		super(Integer.MAX_VALUE, 0, 4, 0, 4);

	}

	@Override
	protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
		ByteBuf bytebuf = (ByteBuf) super.decode(ctx, in);
		byte[] bytes = null;
		if (bytebuf.hasArray()) {
			bytes = bytebuf.array();
		} else {
			 int length = bytebuf.readableBytes();
			 bytes = new byte[length];
			 bytebuf.getBytes(bytebuf.readerIndex(), bytes);
		}
		return deserialize(bytes);
	}

	private Object deserialize(byte[] bytes) {
		ByteArrayInputStream bi = null;
		ObjectInputStream oi = null;
		try {
			bi = new ByteArrayInputStream(bytes);
			oi = new ObjectInputStream(bi);
			Object obj = oi.readObject();
			return obj;
		} catch (Exception e) {
			log.warning("Deserialize to object occur error." + e);
			return null;
		} finally {
			if (null != bi) {
				try {
					bi.close();
				} catch (IOException e) {
				}
			}
			if (null != oi) {
				try {
					oi.close();
				} catch (IOException e) {
				}
			}
		}
	}
}
